package com.yanqu.road.server.gameplayer.module.activity.tomb;

import com.yanqu.road.entity.activity.ActivityDisperseGoldInfo;
import com.yanqu.road.entity.activity.ActivityDisperseGoldResult;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.patrons.PatronsInfo;
import com.yanqu.road.entity.config.skill.SkillInfo;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.log.LogTombGetRelic;
import com.yanqu.road.entity.log.LogTombUserRelic;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.player.UserPatronsSkill;
import com.yanqu.road.entity.task.args.UnionRiseRankArgs;
import com.yanqu.road.logic.activity.tomb.config.TombConfig;
import com.yanqu.road.logic.activity.tomb.config.entity.*;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.pb.tomb.Tomb;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.tomb.business.TombGameBusiness;
import com.yanqu.road.server.gameplayer.module.activity.tomb.entity.DbTombInfo;
import com.yanqu.road.server.gameplayer.module.activity.tomb.entity.DbTombRelic;
import com.yanqu.road.server.gameplayer.module.activity.tomb.entity.TombRelic;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.DecorationModule;
import com.yanqu.road.server.manger.ServerLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.curio.CurioMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SkillMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.serialize.ItemWeight;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class TombModule extends GeneralModule {
    private static Logger logger = LogManager.getLogger(TombModule.class.getName());


    private Map<Integer, DbTombRelic> dbTombRelicMap = new ConcurrentHashMap<>();

    private DbTombInfo dbTombInfo;

    public TombModule(GamePlayer player) {
        super(player);
    }

    @Override
    public boolean loadData() {

        reloadData();
        return true;
    }

    @Override
    public boolean afterLoadData() {
        return false;
    }

    @Override
    public boolean saveData() {

        TombGameBusiness.saveDbTombInfo(dbTombInfo);

        for (DbTombRelic value : this.dbTombRelicMap.values()) {
            TombGameBusiness.saveDbTombRelic(value);
        }
        return true;
    }

    //初始化或读取用户遗物
    public void reloadData() {
        dbTombInfo = TombGameBusiness.getDbTombInfo(this.player.getUserId());
        if (dbTombInfo == null) {
            int activityId = 0;
            if (TombMgr.getActivityInfo() != null) {
                activityId = TombMgr.getActivityInfo().getActivityId();
            }
            dbTombInfo = this.initDbTombInfo(activityId);
        }
        Map<Integer, DbTombRelic> dbTombRelicMap = TombGameBusiness.getDbTombRelic(player.getUserId());
        for (DbTombRelic value : dbTombRelicMap.values()) {
            this.dbTombRelicMap.put(value.getActivityId(), value);
        }

    }

    @Override
    public void afterLogin() {
//        this.syncActivityInfo();
    }

    public int isOpen(boolean needPlaytime) {
        if (StringUtils.isNullOrEmpty(player.getUserInfo().getUnionUid())) {
            return GameErrorCode.E_TOMB_ACTIVITY_NOT_JOIN_UNION;
        }
        if (!needPlaytime) {
            return 0;
        }

        int openTime = TombMgr.getConfig().getConfig().getTOMB_DAILY_OPEN_TIME();
        int endTime = TombMgr.getConfig().getConfig().getTOMB_DAILY_END_TIME();

        LocalDateTime now = LocalDateTime.now();

        int hour = now.getHour();
        if (hour < openTime) {
            return GameErrorCode.E_TOMB_ACTIVITY_TAKE_A_REST;
        }
        if (hour >= endTime) {
            return GameErrorCode.E_TOMB_ACTIVITY_TAKE_A_REST;
        }
        return 0;
    }

    public DbTombInfo initDbTombInfo(int activityId) {
        DbTombInfo dbTombInfo = DbTombInfo.newInstance();
        dbTombInfo.setNeedInsert(true);
        dbTombInfo.setUserId(this.player.getUserId());
        if (this.dbTombInfo != null) {
            dbTombInfo.setChoseEventFinish(this.dbTombInfo.getChoseEventFinish());
            dbTombInfo.setDollMap(this.dbTombInfo.getDollMap());
        }
        dbTombInfo.setActivityId(activityId);
        dbTombInfo.refreshUpdateTime();
        return dbTombInfo;
    }

    public DbTombRelic initDbTombRelic() {

        DbTombRelic dbUserRelic = DbTombRelic.newInstance();
        dbUserRelic.setActivityId(TombMgr.getActivityInfo().getActivityId());
        dbUserRelic.setUserId(getUserId());
        dbUserRelic.setScore(0);
        dbUserRelic.setRelicItemMap(new ConcurrentHashMap<>());
        dbUserRelic.setNeedInsert(true);
        return dbUserRelic;
    }

    public Tomb.PlayerBaseTempMsg.Builder getPlayerBaseTempBuilder() {
        UserInfo userInfo = UserMgr.getUserInfo(player.getUserId());
        PlayerProto.PlayerBaseTempMsg.Builder parsePlayerBaseTempMsg = PlayerPb.parsePlayerBaseTempMsg(userInfo);
        Tomb.PlayerBaseTempMsg.Builder tombPlayerData = Tomb.PlayerBaseTempMsg.newBuilder();
        tombPlayerData.setUserAliasId(parsePlayerBaseTempMsg.getUserAliasId());
        tombPlayerData.setNickName(parsePlayerBaseTempMsg.getNickName());
        tombPlayerData.setTitleId(parsePlayerBaseTempMsg.getTitleId());
        tombPlayerData.setDecoration(parsePlayerBaseTempMsg.getDecoration());
        tombPlayerData.setUnionName(parsePlayerBaseTempMsg.getUnionName());
        tombPlayerData.setUnionUid(parsePlayerBaseTempMsg.getUnionUid());
        tombPlayerData.setUnionAliasId(parsePlayerBaseTempMsg.getUnionAliasId());
        tombPlayerData.setVipExp(parsePlayerBaseTempMsg.getVipExp());
        tombPlayerData.setSex(parsePlayerBaseTempMsg.getSex());
        tombPlayerData.setEarnSpeed(parsePlayerBaseTempMsg.getEarnSpeed());
        tombPlayerData.setRegisterTime(parsePlayerBaseTempMsg.getRegisterTime());
        tombPlayerData.setServerId(parsePlayerBaseTempMsg.getServerId());
        tombPlayerData.setWorld(parsePlayerBaseTempMsg.getWorld());
        tombPlayerData.setContinent(parsePlayerBaseTempMsg.getContinent());
        tombPlayerData.setCountry(parsePlayerBaseTempMsg.getCountry());
        tombPlayerData.setProvince(parsePlayerBaseTempMsg.getProvince());
        tombPlayerData.setCity(parsePlayerBaseTempMsg.getCity());
        tombPlayerData.setLastLoginTime(parsePlayerBaseTempMsg.getLastLoginTime());
        tombPlayerData.setPrestige(parsePlayerBaseTempMsg.getPrestige());
        tombPlayerData.setHideVipAndAddress(parsePlayerBaseTempMsg.getHideVipAndAddress());
        tombPlayerData.setTotalAbility(parsePlayerBaseTempMsg.getTotalAbility());
        tombPlayerData.setTotalIntimacy(parsePlayerBaseTempMsg.getTotalIntimacy());
        tombPlayerData.setUnionHonerPoint(parsePlayerBaseTempMsg.getUnionHonerPoint());
        tombPlayerData.setBadge(parsePlayerBaseTempMsg.getBadge());
        return tombPlayerData;
    }


    public Map<Integer, List<UserPatrons>> getTop6UserPatrons() {
        Map<Integer, UserPatrons> userPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
        List<UserPatrons> list = new ArrayList<>(userPatronsMap.values());
        list.sort((o1, o2) -> o2.getAbility().compareTo(o1.getAbility()));
        Map<Integer, List<UserPatrons>> resultMap = new HashMap<>();
        int jobPatronsLimit = TombMgr.getConfig().getConfig().getTOMB_JOB_PATRONS_LIMIT();
        for (UserPatrons userPatrons : list) {
            PatronsInfo patronsInfo = PatronsMgr.getPatronsInfo(userPatrons.getPatronsId());
            if (patronsInfo != null) {
                if (!resultMap.containsKey(patronsInfo.getOccupation())) {
                    resultMap.put(patronsInfo.getOccupation(), new ArrayList<>());
                }
                if (resultMap.get(patronsInfo.getOccupation()).size() >= jobPatronsLimit) {
                    continue;
                }
                resultMap.get(patronsInfo.getOccupation()).add(userPatrons);
            }
        }
        return resultMap;
    }


    public List<Tomb.PartnerTemp> getPartnerList() {
        List<Tomb.PartnerTemp> list = new ArrayList<>();
        List<Integer> limitParam = TombMgr.getConfig().getConfig().getTOMB_PATRONS_ABILITY_LIMIT_PARAM();
        double p1 = limitParam.get(0);
        double p2 = limitParam.get(1);
        double p3 = limitParam.get(2);
        double p4 = limitParam.get(3);
        double p5 = limitParam.get(4);
        double p6 = limitParam.get(5);
        double p7 = limitParam.get(6);
        for (List<UserPatrons> userPatronsList : this.getTop6UserPatrons().values()) {
            for (UserPatrons userPatrons : userPatronsList) {
                Tomb.PartnerTemp.Builder temp = Tomb.PartnerTemp.newBuilder();
                temp.setId(userPatrons.getPatronsId());
                double ability = userPatrons.getAbility().doubleValue();
                if (ability <= p4) {
                    double step1 = ability / p5;
                    double step2 = Math.log(step1);
                    double step3 = step2 * p6;
                    double step4 = Math.max(step3, p7);
                    temp.setBaseEarn((int) step4);
                    list.add(temp.build());
                } else {
                    double step1 = ability / p1;
                    double step2 = Math.log(step1);
                    double step3 = step2 * p2;
                    double step4 = Math.max(step3, p3);
                    temp.setBaseEarn((int) step4);
                    list.add(temp.build());
                }
            }
        }
        return list;
    }

    public List<Tomb.PartnerTemp> getUpdatePartnerList() {
        List<Tomb.PartnerTemp> list = new ArrayList<>();

        DbTombInfo dbTombInfo = this.getDbTombInfo(TombMgr.getActivityInfo().getActivityId());

        for (Integer partnerId : dbTombInfo.getPartnerIdList()) {
            UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(partnerId);
            Tomb.PartnerTemp.Builder temp = TombMgr.patronAbilityCorrection(userPatrons);
            list.add(temp.build());
        }
        return list;
    }

    /**
     * 计算本次活动总遗物点
     */


    public long calculateRelicScore() {

        DbTombRelic dbTombRelic = this.getDbTombRelic(TombMgr.getActivityInfo().getActivityId());
        if (dbTombRelic.getRelicItemMap().isEmpty()) {
            return 0;
        }
        if (TombMgr.getActivityInfo() == null) {
            return 0;
        }
        long score = 0;
        for (TombRelic tombRelic : dbTombRelic.getRelicItemMap().values()) {
            GoodsInfo good = GoodsMgr.getGoodsById(tombRelic.getItemId());
            score += tombRelic.getItemNum() * good.getParamList().get(0).intValue();
        }
        dbTombRelic.setScore(score);
        dbTombRelic.refreshUpdateTime();
        player.notifyListener(eGamePlayerEventType.TombRelicNum.getValue(), score);
//        this.syncActivityInfo();
        return score;
    }

    /**
     * 秦始皇陵获得遗物
     */
    public void userGetRelicItem(List<Tomb.Item> itemList) {
        List<String> logRelicList = new ArrayList<>();
        DbTombRelic dbTombRelic = this.getDbTombRelic(TombMgr.getActivityInfo().getActivityId());
        Map<Integer, TombRelic> userRelicItemMap = dbTombRelic.getRelicItemMap();
        long score = 0;
        for (Tomb.Item item : itemList) {
            //如果有过道具
            if (userRelicItemMap.containsKey(item.getId())) {
                int oldNum = userRelicItemMap.get(item.getId()).getItemNum();
                userRelicItemMap.get(item.getId()).setItemNum(oldNum + item.getNum());
            } else { //新增道具
                userRelicItemMap.put(item.getId(), new TombRelic(item.getId(), item.getNum()));
            }
            GoodsInfo good = GoodsMgr.getGoodsById(item.getId());
            if (good == null) {
                continue;
            }
            long score1 = (long) item.getNum() * good.getParamList().get(0).intValue();
            score += score1;
            logRelicList.add(item.getId() + "=" + item.getNum());


            LogTombUserRelic logTombUserRelic = new LogTombUserRelic();
            logTombUserRelic.setUserId(player.getUserId());
            logTombUserRelic.setActivityId(TombMgr.getActivityInfo().getActivityId());
            logTombUserRelic.setUnionUid(player.getUserInfo().getUnionUid());
            logTombUserRelic.setRewards(String.valueOf(item.getId()));
            logTombUserRelic.setQuality(good.getQuality());
            logTombUserRelic.setPoint((int) score1);
            AutoLogMgr.add(logTombUserRelic);
        }
        dbTombRelic.setScore(dbTombRelic.getScore() + score);
        dbTombRelic.refreshUpdateTime();

        Property property = new Property();
        property.addProperty(eItemId.TOMB_RELIC_SCORE.getValue(), BigInteger.valueOf(score));

        player.getModule(CurrencyModule.class).addCurrency(property, eLogMoneyType.Tomb, eLogMoneyType.TombUseEnergyPackage);
        player.notifyListener(eGamePlayerEventType.TombRelicNum.getValue(), dbTombRelic.getScore());

        AutoLogMgr.add(new LogTombGetRelic(player.getUserId(), TombMgr.getActivityInfo().getActivityId(), logRelicList));


    }

    /**
     * 获取玩家历史活动的遗物
     */
    public Tomb.GetUserRelicHistoryResp.Builder getUserRelicHistory() {
        Tomb.GetUserRelicHistoryResp.Builder builder = Tomb.GetUserRelicHistoryResp.newBuilder();
        builder.setRet(0);
        for (DbTombRelic userRelic : this.getExpireDbTombRelic()) {
            int activityId = TombMgr.getActivityInfo().getActivityId();
            if (userRelic.getActivityId() != activityId) {
                builder.addUserRelic(parseUserRelicProto(userRelic));
            }
        }
        return builder;
    }

    //秦始皇升级要用到,活动内返回实时计算
    public long getTotalRelicScore() {
        long totalScore = 0;
        for (DbTombRelic dbTombRelic : this.dbTombRelicMap.values()) {
            totalScore += dbTombRelic.getScore();
        }
        return totalScore;
    }

    /**
     * 同步玩家遗物信息
     */
    public Tomb.SyncUserRelicInfoResp.Builder getUserRelicSync() {

        Tomb.SyncUserRelicInfoResp.Builder builder = Tomb.SyncUserRelicInfoResp.newBuilder();
        DbTombRelic dbTombRelic = this.getDbTombRelic(TombMgr.getActivityInfo().getActivityId());
        builder.setUserRelic(parseUserRelicProto(dbTombRelic));
        builder.setRet(0);
        return builder;
    }

    private Tomb.UserRelicInfo.Builder parseUserRelicProto(DbTombRelic userRelic) {
        Tomb.UserRelicInfo.Builder builder = Tomb.UserRelicInfo.newBuilder();
        builder.setActivityId(userRelic.activityId);
        builder.setUserId(userRelic.getUserId());
        for (TombRelic tombRelic : userRelic.getRelicItemMap().values()) {
            Tomb.RelicItemInfo.Builder infoBuilder = Tomb.RelicItemInfo.newBuilder();
            infoBuilder.setItemId(tombRelic.getItemId());
            infoBuilder.setItemNum(tombRelic.getItemNum());
            builder.addRelicItem(infoBuilder);
        }
        builder.setScore(userRelic.score);

        return builder;
    }

    public void getConfigInfo(Tomb.TombConfigInfoResp.Builder builder) {
        String language = player.getUserInfo().getLanguage();
        TombConfig config = TombMgr.getConfig();
        for (ActivityTombEvent configEvent : config.getEvents()) {
            Tomb.TombEventConfigTemp.Builder temp = Tomb.TombEventConfigTemp.newBuilder();
            temp.setId(configEvent.getId());
            temp.setEventType(configEvent.getEventType());
            temp.setNpcId(configEvent.getNpcId());
            temp.setNpcBookmark(configEvent.getNpcBookmark());
            temp.addAllScore(configEvent.getScore());
            temp.setReward(PropertyHelper.parsePropertyToString(configEvent.getReward()));
            temp.addAllParam1(configEvent.getParam1());
            temp.setArea(configEvent.getArea());
            for (List<ItemWeight> itemWeightList : configEvent.getMonsterReward()) {
                for (ItemWeight itemWeight : itemWeightList) {
                    Tomb.Item.Builder item = Tomb.Item.newBuilder();
                    item.setId(itemWeight.getItem().getId());
                    item.setNum(itemWeight.getItem().getNum());
                    item.setExt(String.valueOf(itemWeight.getWeight()));
                    temp.addMonsterReward(item);
                }
            }
            builder.addEventConfigList(temp);
        }

        for (ActivityTombBookmark bookmark : config.getBookmarks()) {
            Tomb.TombBookmarkConfigTemp.Builder temp = Tomb.TombBookmarkConfigTemp.newBuilder();
            temp.setId(bookmark.getId());
            temp.setName(ServerLanguageMgr.getContent(bookmark.getName(), language));
            temp.setEventType(bookmark.getEventType());
            temp.setSubclassName(ServerLanguageMgr.getContent(bookmark.getSubclassName(), language));
            temp.setSubclassDesc(ServerLanguageMgr.getContent(bookmark.getSubclassDesc(), language));
            temp.setIcon(bookmark.getIcon());
            temp.setQuality(bookmark.getQuality());
            builder.addBookmarkConfigList(temp);
        }

        for (ActivityTombFloor floor : config.getFloors()) {
            Tomb.TombFloorConfigTemp.Builder temp = Tomb.TombFloorConfigTemp.newBuilder();
            temp.setId(floor.getId());
            temp.addAllFloor(floor.getFloor());
            temp.setEnergy(floor.getEnergy());
            for (List<Integer> integerList : floor.getEventWeight()) {
                Tomb.IntArray.Builder intArray = Tomb.IntArray.newBuilder();
                intArray.addAllIntArray(integerList);
                temp.addEventWeight(intArray);
            }
            builder.addFloorConfigList(temp);
        }

        for (ActivityTombRepair repair : config.getRepairs()) {
            Tomb.TombRepairConfigTemp.Builder temp = Tomb.TombRepairConfigTemp.newBuilder();
            temp.setId(repair.getId());
            temp.setDesc(ServerLanguageMgr.getContent(repair.getDesc(), language));
            temp.setMaxSchedule(repair.getSchedule());
            temp.setName(ServerLanguageMgr.getContent(repair.getName(), language));
            builder.addRepairConfigList(temp);
        }

        for (ActivityTombRank activityTombRank : config.getRanks()) {
            Tomb.TombRankConfigTemp.Builder temp = Tomb.TombRankConfigTemp.newBuilder();
            temp.setId(activityTombRank.getId());
            temp.setTitle(activityTombRank.getTitle());
            temp.setDesc(activityTombRank.getDesc());
            temp.setType(activityTombRank.getType());
            temp.setRewards(PropertyHelper.parsePropertyToString(activityTombRank.getRewards()));
            temp.addAllParams(activityTombRank.getParams());
            builder.addRankConfigList(temp);
        }

    }


    public void updateScoreAndUnionScore(long score, long unionScore) {
        DbTombInfo dbTombInfo = this.getDbTombInfo(TombMgr.getActivityInfo().getActivityId());

        if (score > dbTombInfo.getScore()) {
            dbTombInfo.setScore(score);
            this.updatePersonalRank(score);
        }

        if (unionScore != dbTombInfo.getUnionScore()) {
            dbTombInfo.setUnionScore(unionScore);
            this.updateUnionRank(unionScore);
        }
        dbTombInfo.refreshUpdateTime();
    }


    /**
     * 更新个人排行榜方法
     */
    public void updatePersonalRank(long userScore) {
        player.notifyListener(eGamePlayerEventType.TombUserRank.getValue(), userScore);

    }

    /**
     * 更新商会排行榜方法
     */
    public void updateUnionRank(long unionScore) {
        player.notifyListener(eGamePlayerEventType.TombUnionRank.getValue(),
                new UnionRiseRankArgs(UnionRiseRankArgs.NOTIFY_TYPE_NORMAL, BigInteger.valueOf(unionScore), player.getUserInfo().getUnionUid()));
    }

    /**
     * 获取门客技能加成
     */
    public List<Integer> getTombSkillAddition() {
        int ackAddition = 0;
        int hpAddition = 0;

        Map<Integer, UserPatrons> userPatronsMap = player.getModule(PatronsModule.class).getUserPatronsMap();
        for (UserPatrons patrons : userPatronsMap.values()) {
            for (UserPatronsSkill patronsSkill : patrons.getSkillList()) {
                SkillInfo skillInfo = SkillMgr.getSkillInfo(patronsSkill.getSkillId());
                if (skillInfo == null) {
                    continue;
                }
                if (skillInfo.getType() == eSkillType.TombAddPlayerAck.getValue()) {
                    ackAddition += SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
                } else if (skillInfo.getType() == eSkillType.TombAddPlayerHp.getValue()) {
                    hpAddition += SkillMgr.getSkillAddition(skillInfo, patronsSkill.getSkillLv());
                }
            }
        }
        ackAddition += CurioMgr.getSkillAdditionBySkillType(eSkillType.TombAttackBloodSkill.getValue(), player, 0);
        hpAddition += CurioMgr.getSkillAdditionBySkillType(eSkillType.TombAttackBloodSkill.getValue(), player, 0);

        List<Integer> addtionLists = new ArrayList<>();
        addtionLists.add(ackAddition);
        addtionLists.add(hpAddition);

        return addtionLists;
    }

    //物品栏获得 不需要返回
    public void addDoll(int dollId, BigInteger count) {
        long addTime = 0;
        try {
            addTime = 1000L * GoodsMgr.getGoodsById(dollId).getParamList().get(0).longValue() * count.longValue();
        } catch (Exception e) {
            logger.error("addDoll error on addDoll! GoodsInfo is null!");
        }
        if (!this.dbTombInfo.getDollMap().containsKey(dollId)) {
            this.dbTombInfo.getDollMap().put(dollId, 0L);
        }
        long now = System.currentTimeMillis();
        if (this.dbTombInfo.getDollMap().get(dollId) < now) {
            this.dbTombInfo.getDollMap().put(dollId, now + addTime);
        } else {
            this.dbTombInfo.getDollMap().put(dollId, this.dbTombInfo.getDollMap().get(dollId) + addTime);
        }
        this.dbTombInfo.refreshUpdateTime();
    }

    public DbTombInfo getDbTombInfo(int activityId) {
        if (this.dbTombInfo.getActivityId() > 0 && this.dbTombInfo.getActivityId() != activityId) {
            this.dbTombInfo = this.initDbTombInfo(activityId);
            return dbTombInfo;
        }
        if (dbTombInfo.getActivityId() == 0) {
            dbTombInfo.setActivityId(activityId);
            dbTombInfo.refreshUpdateTime();
        }
        return dbTombInfo;
    }




    public DbTombRelic getDbTombRelic(int activityId) {
        DbTombRelic dbTombRelic = this.dbTombRelicMap.get(activityId);
        if (dbTombRelic == null) {
            dbTombRelic = this.initDbTombRelic();
            this.dbTombRelicMap.put(dbTombRelic.getActivityId(), dbTombRelic);
            return dbTombRelic;
        }
        return dbTombRelic;
    }


    public List<DbTombRelic> getExpireDbTombRelic() {
        List<DbTombRelic> list = new ArrayList<>();
        for (DbTombRelic value : this.dbTombRelicMap.values()) {
            if (value.getActivityId() == TombMgr.getActivityInfo().getActivityId()) {
                continue;
            }
            list.add(value);
        }
        return list;
    }


    public Property addRewards(String rewards) {
        Property property = PropertyHelper.parseStringToProperty(rewards);
        Property showProperty = new Property();
        Property property1 = new Property();
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            if (entry.getKey() == TombMgr.getConfig().getConfig().getTOMB_SCORE_ITEM_ID()) {
                showProperty.addProperty(entry.getKey(), entry.getValue());
                continue;
            }
            if (entry.getKey() == TombMgr.getConfig().getConfig().getTOMB_GUILD_SCORE_ITEM_ID()) {
                showProperty.addProperty(entry.getKey(), entry.getValue());
                continue;
            }

            //改成了在活动服里随机，这里不需要再拆礼包了
//            if (GoodsMgr.isGoodsBag(entry.getKey())) {
//                OpenGoodsBagResult openResult = GoodsBagMgr.getRandomGoods(entry.getKey());
//                property1.addProperty(openResult.getReward());
//                showProperty.addProperty(openResult.getReward());
//                continue;
//            }
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(entry.getKey());
            if (goodsInfo != null && goodsInfo.getType() == eGoodsType.TombRelic.getValue()) {
                List<Tomb.Item> itemList = new ArrayList<>();
                Tomb.Item.Builder temp = Tomb.Item.newBuilder();
                temp.setId(entry.getKey());
                temp.setNum(1);
                itemList.add(temp.build());
                this.userGetRelicItem(itemList);
                showProperty.addProperty(entry.getKey(), entry.getValue());
                continue;
            }
            showProperty.addProperty(entry.getKey(), entry.getValue());
            property1.addProperty(entry.getKey(), entry.getValue());
        }
        this.player.getModule(CurrencyModule.class).addCurrency(property1, eLogMoneyType.Tomb, eLogMoneyType.TombEventReward);
        return showProperty;
    }

    public Property addTakeCareRewards(String rewards) {
        Property property = PropertyHelper.parseStringToProperty(rewards);
        Property showProperty = new Property();
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            if (entry.getKey() == TombMgr.getConfig().getConfig().getTOMB_SCORE_ITEM_ID()) {
                showProperty.addProperty(entry.getKey(), entry.getValue());
                continue;
            }
            if (entry.getKey() == TombMgr.getConfig().getConfig().getTOMB_GUILD_SCORE_ITEM_ID()) {
                showProperty.addProperty(entry.getKey(), entry.getValue());
                continue;
            }
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(entry.getKey());
            if (goodsInfo != null && goodsInfo.getType() == eGoodsType.TombRelic.getValue()) {
                List<Tomb.Item> itemList = new ArrayList<>();
                Tomb.Item.Builder temp = Tomb.Item.newBuilder();
                temp.setId(entry.getKey());
                temp.setNum(1);
                itemList.add(temp.build());
                this.userGetRelicItem(itemList);
                showProperty.addProperty(entry.getKey(), entry.getValue());
                continue;
            }
            showProperty.addProperty(entry.getKey(), entry.getValue());
        }
        return showProperty;
    }

    public void putInTakeItemBag(String rewards) {
        Property property = PropertyHelper.parseStringToProperty(rewards);
        for (Map.Entry<Integer, BigInteger> entry : property.getGoods().entrySet()) {
            if (entry.getKey() == TombMgr.getConfig().getConfig().getTOMB_SCORE_ITEM_ID()) {
                continue;
            }
            if (entry.getKey() == TombMgr.getConfig().getConfig().getTOMB_GUILD_SCORE_ITEM_ID()) {
                continue;
            }
            GoodsInfo goodsInfo = GoodsMgr.getGoodsById(entry.getKey());
            if (goodsInfo != null && goodsInfo.getType() == eGoodsType.TombRelic.getValue()) {
                continue;
            }
            DbTombInfo dbTombInfo = this.getDbTombInfo(TombMgr.getActivityInfo().getActivityId());
            long oldValue = 0;
            if (dbTombInfo.getTakeCareItemMap().containsKey(entry.getKey())) {
                oldValue = dbTombInfo.getTakeCareItemMap().get(entry.getKey());
            }
            long value = entry.getValue().add(BigInteger.valueOf(oldValue)).longValue();
            dbTombInfo.getTakeCareItemMap().put(entry.getKey(), value);
        }
    }

    /**
     * 牌圣送财
     *
     * @param activityInfo 活动信息
     * @return ActivityDisperseGoldResult
     */
    public ActivityDisperseGoldResult disperseGold(ActivityInfo activityInfo, String manifesto) {
        ActivityDisperseGoldResult result = new ActivityDisperseGoldResult();
        if (activityInfo.getActivityId() != TombMgr.getActivityInfo().getActivityId()) {
            result.setRet(GameErrorCode.E_ACTIVITY_OVER_TIME);
            return result;
        }
        if (!ActivityMgr.activityInTime(activityInfo)) {
            result.setRet(GameErrorCode.E_ACTIVITY_OVER_TIME);
            return result;
        }
        List<Integer> decorationIdList = player.getModule(DecorationModule.class).getDecorationIdList(eDecorationType.HonoraryTitle.getValue());
        ActivityDisperseGoldInfo goldInfo = new ActivityDisperseGoldInfo();
        goldInfo.setActivityId(activityInfo.getActivityId());
        goldInfo.setType(activityInfo.getType());
        goldInfo.setUserId(player.getUserId());
        goldInfo.setManifesto(manifesto);
        goldInfo.setBeginTime(System.currentTimeMillis());
        goldInfo.setHonoraryTitles(StringUtils.listToString(decorationIdList, ","));
        int groupId = GameUnionActivityGroupMgr.getGroupId(activityInfo.getActivityId(), player.getUserId());
        goldInfo.setServerList(TombMgr.getServerIdSet(activityInfo, groupId));
        goldInfo.setUserBaseInfo(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId()));
        goldInfo.setGroupId(groupId);
        result.setGoldInfo(goldInfo);
        return result;
    }


    public void syncActivityInfo() {
        Tomb.TombActivityInfoResp.Builder builder = Tomb.TombActivityInfoResp.newBuilder();
        if (TombMgr.getActivityInfo() != null) {
            ActivityInfo activityInfo = TombMgr.getActivityInfo();
            DbTombInfo dbTombInfo = this.getDbTombInfo(activityInfo.getActivityId());
            builder.setPersonalScore(dbTombInfo.getScore());
            builder.setUnionScore(dbTombInfo.getUnionScore());
        }
        long totalRelicScore = this.getTotalRelicScore();
        builder.setRelicPoint(totalRelicScore);
        player.sendPacket(ClientProtocol.U_TOMB_ACTIVITY_INFO, builder);
    }


}
